import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Toast } from 'vant'
// 导入路由组件
const login = () => import('@/views/login')
const layout = () => import('@/views/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const video = () => import('@/views/video')
const my = () => import('@/views/my')
const edit = () => import('@/views/my/edit')
const detail = () => import('@/views/detail')
const xiaozhi = () => import('@/views/my/xiaozhi')
const search = () => import('@/views/search')
const result = () => import('@/views/search/result')


Vue.use(VueRouter)

const routes = [
  { path: '', redirect: '/layout/home' },
  { path: '/login', component: login },
  {
    path: '/layout', component: layout, children: [
      { path: 'home', component: home, meta: { needKeep: true } },
      { path: 'ask', component: ask },
      { path: 'video', component: video },
      { path: 'my', component: my, meta: { needLogin: true } }
    ]
  },
  { path: '/my/edit', component: edit, meta: { needLogin: true } },
  { path: '/home/detail', component: detail },
  { path: '/home/search', component: search },
  { path: '/search/result', component: result },
  { path: '/my/xiaozhi', component: xiaozhi, meta: { needLogin: true } }
]

const router = new VueRouter({
  routes
})

// 添加导航守卫
router.beforeEach((to, from, next) => {
  // console.log(to)
  const needLogin = to.meta.needLogin
  if (needLogin) {
    // 得到token
    const token = store.state.token.token
    // 有token
    if (token) {
      next()
    } else {
      // 无token
      Toast.fail("您还未登录~");
      // 保存当前访问的路径
      const path = to.path
      next(`/login?url=${path}`)
    }
  } else {
    next()
  }
})

export default router
